import router from '@/router'
import store from './store'
import { userInfo } from './api'
import getPageTitle from '@/utils/get-page-title'
import { getToken } from './utils/auth'

const whiteList = ['/home', '/goods', '/login', '/goodsDetails']
// eslint-disable-next-line space-before-function-paren
router.beforeEach(async (to, from, next) => {
  document.title = getPageTitle(to.meta.title)

  // 白名单
  if (whiteList.includes(to.path)) {
    next()
  } else {
    const token = getToken()
    userInfo({ token }).then(res => {
      // 没登录
      if (!res.success) {
        next('/login')
      } else {
        store.commit('RECORD_USERINFO', { info: res.data })
        //  跳转到
        if (to.path === '/login') {
          next({ path: '/' })
        } else {
          next()
        }
      }
    })
  }
})
